package dao

import (
	"time"
	"wish_go/src/main/com/ajie/common"
	"wish_go/src/main/com/ajie/model"
	"wish_go/src/main/com/ajie/vo"
)

type pageDto struct {
	Id           uint      `json:"id"`
	Title        string    `json:"title"`
	Content      string    `json:"content"`
	Images       string    `json:"images"`
	Type         bool      `json:"type"`
	IsAnonymous  bool      `json:"isAnonymous"`
	Openid       string    `json:"openid"`
	CreatedAt    string    `json:"createdAt"`
	NickName     string    `json:"nickName"`
	Avatar       string    `json:"avatar"`
	IsExposure   bool      `json:"isExposure"`
	ExposureTime time.Time `json:"exposureTime"`
}

func PageWish(wish *vo.Wish, pagination *vo.Pagination) (rows []pageDto, total int64, dbErr error) {
	offset := (pagination.PageNum - 1) * pagination.PageSize
	db := common.GetDB()
	joins := db.Table("wishes").Select("wishes.id", "wishes.title", "wishes.content", "wishes.images", "wishes.type", "wishes.is_anonymous", "wishes.openid", "wishes.created_at", "wishes.is_exposure", "wishes.exposure_time", "users.nick_name", "users.avatar").Joins("left join users on wishes.openid=users.openid")
	if len(wish.Openid) > 0 {
		joins.Where("wishes.openid = ?", wish.Openid)
	}
	if len(wish.Keywords) > 0 {
		joins.Where("wishes.title like '%?%' or wishes.content like '%?%' or users.nick_name like '%?%'", wish.Keywords, wish.Keywords, wish.Keywords)
	}
	joins.Order(pagination.SortName)
	dbErr = joins.Count(&total).Limit(pagination.PageSize).Offset(offset).Scan(&rows).Error
	return
}

func InsertWish(wish model.Wish) (dbErr error) {
	db := common.GetDB()
	dbErr = db.Create(&wish).Error
	return
}

func UpdateWish(wish model.Wish) (i int64, dbErr error) {
	db := common.GetDB()
	updates := db.Model(&wish).Updates(wish)
	if !wish.IsExposure {
		updates.Update("is_exposure = ?", 0)
	}
	i = updates.RowsAffected
	dbErr = updates.Error
	return
}

func WishHotspot(wish model.Wish) (i int64, dbErr error) {
	db := common.GetDB()
	updates := db.Model(&wish).Select("is_exposure", "exposure_time").Updates(wish)
	i = updates.RowsAffected
	dbErr = updates.Error
	return
}

func DeleteWish(wish model.Wish) {
	db := common.GetDB()
	// 删除数据。根据主键删除--存在deleted_at 就软删除
	db.Delete(&wish)
}

type AreaDto struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

func GetAreaByOpenid(openid string) (rows []AreaDto, dbErr error) {
	db := common.GetDB()
	find := db.Distinct("area_code").Select("area_code").Where("openid = ?", openid).Find(&model.Wish{})
	db.Select("name as label", "area_code as value").Where("area_code in (?)", find).Find(&model.Area{}).Scan(&rows)
	return
}
